package day9zy.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;
import java.util.Scanner;

/**
 * @author oldliu
 * @since 1.0
 */
public class Xml {
    public static void main(String[] args) throws DocumentException {
        //读，删除，增加，修改
        read();
        cha();
    }

    public static void read() {
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(new File("C:\\Users\\徐恩德\\IdeaProjects\\javaxx\\javagj\\src\\day9zy\\products.xml"));
            Element root = doc.getRootElement();
            System.out.println(root.getName());
            List<Node> shops = root.selectNodes("product");
            for (Node n : shops) {
                Element e = (Element) n;
                String discount = e.attributeValue("discount");
                String factoryaddr = e.attributeValue("factoryaddr");
                String itemno = e.selectSingleNode("itemno").getText();
                String name = e.selectSingleNode("name").getText();
                String price = e.selectSingleNode("price").getText();
                String stockcount = e.selectSingleNode("stockcount").getText();
                String unit = e.selectSingleNode("unit").getText();
                double money =Double.parseDouble(price);
                System.out.println("factoryaddr"+factoryaddr+"discount"+discount+"itemno"+itemno+"name"+name+"stockcount"+stockcount+"unit"+unit+"money"+money);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    public static void cha() throws DocumentException {
        System.out.println("请输入商品号：");
        Scanner in  =new Scanner(System.in);
        String num  = in.next();
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("C:\\Users\\徐恩德\\IdeaProjects\\javaxx\\javagj\\src\\day9zy\\products.xml"));
        Element root = doc.getRootElement();
        List<Node> shops = root.selectNodes("product");
        for (Node n : shops) {
            Element e = (Element) n;
        String itemno = e.selectSingleNode("itemno").getText();
            String discount = e.attributeValue("discount");
            String factoryaddr = e.attributeValue("factoryaddr");
            String name = e.selectSingleNode("name").getText();
            String price = e.selectSingleNode("price").getText();
            String stockcount = e.selectSingleNode("stockcount").getText();
            String unit = e.selectSingleNode("unit").getText();
            double money =Double.parseDouble(price);
        if (itemno.equals(num)){
            System.out.println("factoryaddr"+factoryaddr+"discount"+discount+"itemno"+itemno+"name"+name+"stockcount"+stockcount+"unit"+unit+"money"+money);
        }
    }}
}
